package xs.szw.service.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import xs.szw.common.constant.RedisKeyConstant;
import xs.szw.service.model.bo.RolePermsBO;
import xs.szw.service.model.pojo.sys.RoleMenu;
import xs.szw.service.service.RoleMenuService;
import xs.szw.service.mapper.RoleMenuMapper;
import org.springframework.stereotype.Service;
import xs.szw.service.utils.RedisCache;

import java.util.List;
import java.util.Set;

/**
* @author asus
* @description 针对表【sys_role_menu(角色和菜单关联表)】的数据库操作Service实现
* @createDate 2025-02-11 10:18:06
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu>
    implements RoleMenuService{


    private final RedisCache redisCache;


    private final RoleMenuMapper roleMenuMapper;

    /**
     * 初始化权限缓存
     */
    @PostConstruct
    public void initRolePermsCache() {
        log.info("初始化权限缓存... ");
        refreshRolePermsCache();
    }

    /**
     * 刷新权限缓存(所有角色)
     */
    @Override
    public void refreshRolePermsCache() {
        //手动清理缓存
        redisCache.delCacheMapValue(RedisKeyConstant.ROLE_PERMS_PREFIX,"*");

        List<RolePermsBO> list = roleMenuMapper.getRolePermsList(null);

        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(item -> {
                String roleCode = item.getRoleCode();
                Set<String> perms = item.getPerms();
                if (CollectionUtil.isNotEmpty(perms)) {
                    redisCache.setCacheMapValue(RedisKeyConstant.ROLE_PERMS_PREFIX,roleCode,perms);
                }
            });
        }
    }

    /**
     * 刷新权限缓存
     */
    @Override
    public void refreshRolePermsCache(String roleCode) {
        // 清理权限缓存
        redisCache.delCacheMapValue(RedisKeyConstant.ROLE_PERMS_PREFIX,roleCode);

        List<RolePermsBO> list = this.baseMapper.getRolePermsList(roleCode);
        if (CollectionUtil.isNotEmpty(list)) {
            RolePermsBO rolePerms = list.get(0);
            if (rolePerms == null) {
                return;
            }

            Set<String> perms = rolePerms.getPerms();
            if (CollectionUtil.isNotEmpty(perms)) {
                redisCache.setCacheMapValue(RedisKeyConstant.ROLE_PERMS_PREFIX, roleCode, perms);
            }
        }
    }

    @Override
    public void refreshRolePermsCache(String oldRoleCode, String newRoleCode) {

    }

    @Override
    public Set<String> getRolePermsByRoleCodes(Set<String> roles) {
        return null;
    }
}




